<template>
  <div v-if="stage === 'instructions'" class="max-w-3xl mx-auto">
    <div class="card bg-white/90 backdrop-blur-sm border-teal-200 shadow-lg">
      <div class="card-header text-center pb-8">
        <div
          class="w-16 h-16 bg-gradient-to-br from-teal-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
        >
          <Shuffle class="w-8 h-8 text-white" />
        </div>
        <h2 class="card-title text-2xl text-slate-800">{{ t("cognitiveFlexibilityTest.title") }}</h2>
        <p class="text-slate-600 mt-2">{{ t("cognitiveFlexibilityTest.description") }}</p>
      </div>

      <div class="card-content space-y-6">
        <div
          class="bg-gradient-to-r from-teal-50 to-cyan-50 rounded-xl p-6 border border-teal-100"
        >
          <h3 class="font-semibold text-teal-900 mb-4 flex items-center gap-2">
            <Star class="w-5 h-5" />
            {{ t("cognitiveFlexibilityTest.instructionsTitle") }}
          </h3>
          <div class="space-y-3 text-slate-700">
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >1</span
              >
              <p>{{ t("cognitiveFlexibilityTest.instruction1") }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >2</span
              >
              <p>{{ t("cognitiveFlexibilityTest.instruction2") }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >3</span
              >
              <p>{{ t("cognitiveFlexibilityTest.instruction3") }}</p>
            </div>
          </div>
        </div>

        <div class="grid md:grid-cols-2 gap-4">
          <div
            class="p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200"
          >
            <h4
              class="font-semibold text-blue-800 mb-2 flex items-center gap-2"
            >
              <div class="w-3 h-3 bg-blue-600 rounded-full"></div>
              {{ t("cognitiveFlexibilityTest.shapeRuleTitle") }}
            </h4>
            <p class="text-sm text-blue-700">{{ t("cognitiveFlexibilityTest.shapeRule") }}</p>
          </div>

          <div
            class="p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200"
          >
            <h4
              class="font-semibold text-purple-800 mb-2 flex items-center gap-2"
            >
              <div class="w-3 h-3 bg-purple-600 rounded-full"></div>
              {{ t("cognitiveFlexibilityTest.colorRuleTitle") }}
            </h4>
            <p class="text-sm text-purple-700">{{ t("cognitiveFlexibilityTest.colorRule") }}</p>
          </div>

          <div
            class="p-4 bg-gradient-to-br from-green-50 to-green-100 rounded-xl border border-green-200"
          >
            <h4
              class="font-semibold text-green-800 mb-2 flex items-center gap-2"
            >
              <div class="w-3 h-3 bg-green-600 rounded-full"></div>
              {{ t("cognitiveFlexibilityTest.sizeRuleTitle") }}
            </h4>
            <p class="text-sm text-green-700">{{ t("cognitiveFlexibilityTest.sizeRule") }}</p>
          </div>

          <div
            class="p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200"
          >
            <h4
              class="font-semibold text-orange-800 mb-2 flex items-center gap-2"
            >
              <div class="w-3 h-3 bg-orange-600 rounded-full"></div>
              {{ t("cognitiveFlexibilityTest.mixedRuleTitle") }}
            </h4>
            <p class="text-sm text-orange-700">{{ t("cognitiveFlexibilityTest.mixedRule") }}</p>
          </div>
        </div>

        <div
          class="bg-gradient-to-r from-amber-50 to-yellow-50 rounded-xl p-6 border border-amber-100"
        >
          <h3 class="font-semibold text-amber-900 mb-4 flex items-center gap-2">
            <Brain class="w-5 h-5" />
            {{ t("cognitiveFlexibilityTest.strategyTitle") }}
          </h3>
          <div class="space-y-2 text-slate-700">
            <p v-html="t('cognitiveFlexibilityTest.strategy1')"></p>
            <p v-html="t('cognitiveFlexibilityTest.strategy2')"></p>
            <p v-html="t('cognitiveFlexibilityTest.strategy3')"></p>
          </div>
        </div>

        <div class="grid md:grid-cols-3 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200"
          >
            <div class="text-2xl font-bold text-teal-600 mb-1">
              {{ t("cognitiveFlexibilityTest.trialsCount") }}
            </div>
            <div class="text-sm text-teal-700">{{ t("cognitiveFlexibilityTest.trialsLabel") }}</div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200"
          >
            <div class="text-2xl font-bold text-cyan-600 mb-1">
              {{ t("cognitiveFlexibilityTest.timeLimit") }}
            </div>
            <div class="text-sm text-cyan-700">{{ t("cognitiveFlexibilityTest.timeLimitLabel") }}</div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-teal-50 to-cyan-50 rounded-xl border border-teal-200"
          >
            <div class="text-2xl font-bold text-slate-600 mb-1">
              {{ t("cognitiveFlexibilityTest.ruleSets") }}
            </div>
            <div class="text-sm text-slate-700">{{ t("cognitiveFlexibilityTest.ruleSetsLabel") }}</div>
          </div>
        </div>

        <button
          class="w-full bg-gradient-to-r from-teal-600 to-cyan-500 hover:from-teal-700 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
          size="lg"
          @click="handleStartTest"
        >
          {{ t("cognitiveFlexibilityTest.startTest") }}
        </button>
      </div>
    </div>
  </div>

  <div
    v-else-if="stage === 'test' && currentTrialData"
    class="max-w-4xl mx-auto space-y-6"
  >
    <!-- 顶部状态栏 -->
    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4 flex-wrap">
        <div
          class="badge badge-outline bg-teal-100 text-teal-700 border-teal-300"
        >
          {{
            t("cognitiveFlexibilityTest.trialProgress", {
              current: currentTrial + 1,
              total: trials.length,
            })
          }}
        </div>
        <div :class="['badge', 'badge-outline', ruleBadgeClass]">
          {{ ruleDefinitions[currentRule].description }}
        </div>
        <transition name="fade">
          <div v-if="isSwitch" class="flex items-center">
            <div
              class="badge badge-outline bg-red-100 text-red-700 border-red-300 flex items-center gap-1"
            >
              <Zap class="w-3 h-3" />
              {{ t("cognitiveFlexibilityTest.ruleSwitch") }}
            </div>
          </div>
        </transition>
        <div
          v-if="streakCount >= 5"
          class="badge badge-outline bg-emerald-100 text-emerald-700 border-emerald-300 flex items-center gap-1"
        >
          <Target class="w-3 h-3" />
          {{ t("cognitiveFlexibilityTest.streak", { count: streakCount }) }}
        </div>
      </div>

      <div class="flex items-center gap-4">
        <div class="flex items-center gap-2 text-slate-600">
          <Trophy class="w-4 h-4" />
          <span class="font-semibold">{{ score }} / {{ currentTrial }}</span>
        </div>
        <div class="flex items-center gap-2">
          <Clock class="w-4 h-4 text-slate-500" />
          <span
            :class="[
              'font-mono',
              'text-lg',
              'font-bold',
              timeLeft <= 60 ? 'text-red-500' : 'text-slate-700',
            ]"
          >
            {{ Math.floor(timeLeft / 60) }}:{{
              (timeLeft % 60).toString().padStart(2, "0")
            }}
          </span>
        </div>
      </div>
    </div>

    <!-- Progress Bar -->
    <div class="relative h-2 w-full overflow-hidden rounded-full bg-gray-200">
      <div
        :style="{ width: progress + '%' }"
        class="h-full bg-teal-500 transition-all duration-300 ease-in-out"
      ></div>
    </div>

    <!-- 规则提示 -->
    <transition name="fade">
      <div
        :key="currentRule"
        :class="['card', 'bg-gradient-to-r', ruleCardClass]"
      >
        <div class="card-content py-4">
          <div class="text-center">
            <h3 :class="['text-lg', 'font-semibold', ruleTextClass]">
              {{
                t("cognitiveFlexibilityTest.currentRule", {
                  criteria: ruleDefinitions[currentRule].criteria,
                })
              }}
            </h3>
          </div>
        </div>
      </div>
    </transition>

    <!-- 测试区域 -->
    <div class="card bg-white/90 backdrop-blur-sm border-teal-200 shadow-lg">
      <div class="card-content py-12">
        <div class="text-center space-y-8">
          <div class="relative h-40 flex items-center justify-center">
            <transition mode="out-in" name="shape-rotate">
              <div
                :key="currentTrialData.id"
                class="flex items-center justify-center"
                style="perspective: 1000px"
              >
                <!-- Simple Shapes -->
                <div
                  v-if="currentTrialData.shape === 'circle' || currentTrialData.shape === 'square'"
                  :class="simpleShapeClasses"
                ></div>

                <!-- Complex Shapes -->
                <div v-else :class="complexShapeContainerClasses">
                  <div
                    v-if="currentTrialData.shape === 'triangle'"
                    :class="['absolute inset-0 shadow-lg', shapeColorClass]"
                    style="clip-path: polygon(50% 0%, 0% 100%, 100% 100%)"
                  ></div>
                  <div
                    v-else-if="currentTrialData.shape === 'diamond'"
                    :class="[
                      'absolute inset-0 shadow-lg transform rotate-45',
                      shapeColorClass,
                    ]"
                    style="border-radius: 8px"
                  ></div>
                  <div
                    v-else-if="currentTrialData.shape === 'hexagon'"
                    :class="['absolute inset-0 shadow-lg', shapeColorClass]"
                    style="clip-path: polygon(50% 0%,100% 25%,100% 75%,50% 100%,0% 75%,0% 25%);"
                  ></div>
                </div>
              </div>
            </transition>

            <!-- Instant Feedback -->
            <transition name="pop">
              <div
                v-if="feedback.show"
                :class="[
                  'absolute',
                  'top-0',
                  'right-0',
                  'w-12',
                  'h-12',
                  'rounded-full',
                  'flex',
                  'items-center',
                  'justify-center',
                  'shadow-lg',
                  feedback.correct ? 'bg-green-500' : 'bg-red-500',
                ]"
              >
                <CheckCircle
                  v-if="feedback.correct"
                  class="w-6 h-6 text-white"
                />
                <XCircle v-else class="w-6 h-6 text-white" />
              </div>
            </transition>

            <!-- Reaction Time Display -->
            <transition name="slide-up">
              <div
                v-if="feedback.show"
                class="absolute -bottom-8 left-1/2 transform -translate-x-1/2"
              >
                <div class="badge badge-outline bg-white/90 text-slate-600">
                  {{ feedback.reactionTime }}ms
                </div>
              </div>
            </transition>
          </div>

          <h2 class="text-xl font-semibold text-slate-800 mb-6">
            {{ t("cognitiveFlexibilityTest.isCorrectPrompt") }}
          </h2>

          <transition name="slide-up">
            <div
              v-if="!feedback.show && awaitingResponse"
              class="flex justify-center gap-6"
            >
              <button
                class="bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white px-12 py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
                size="lg"
                @click="handleResponse(true)"
              >
                {{ t("cognitiveFlexibilityTest.correct") }}
              </button>
              <button
                class="bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white px-12 py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
                size="lg"
                @click="handleResponse(false)"
              >
                {{ t("cognitiveFlexibilityTest.incorrect") }}
              </button>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>

  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <div class="card bg-white/90 backdrop-blur-sm border-teal-200 shadow-xl">
      <div class="card-header text-center pb-6">
        <div
          class="w-20 h-20 bg-gradient-to-br from-teal-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
        >
          <Trophy class="w-10 h-10 text-white" />
        </div>

        <h2 class="card-title text-3xl text-slate-800 mb-2">
          {{ t("cognitiveFlexibilityTest.testComplete") }}
        </h2>
        <div
          class="text-6xl font-bold bg-gradient-to-r from-teal-600 to-cyan-500 bg-clip-text text-transparent"
        >
          {{ results.finalScore }}
        </div>
        <p class="text-slate-600">{{ t("cognitiveFlexibilityTest.scoreLabel") }}</p>
      </div>

      <div class="card-content space-y-6">
        <div class="grid grid-cols-2 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200"
          >
            <div class="text-2xl font-bold text-teal-600 mb-1">
              {{ results.accuracy }}%
            </div>
            <div class="text-sm text-teal-700">{{ t("cognitiveFlexibilityTest.overallAccuracy") }}</div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200"
          >
            <div class="text-2xl font-bold text-cyan-600 mb-1">
              {{ results.averageRT }}ms
            </div>
            <div class="text-sm text-cyan-700">
              {{ t("cognitiveFlexibilityTest.averageResponseTime") }}
            </div>
          </div>
        </div>

        <div class="space-y-3">
          <div
            class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
          >
            <span class="text-slate-600">{{ t("cognitiveFlexibilityTest.correctTrials") }}</span>
            <span class="font-semibold text-slate-800"
              >{{ results.correctResponsesCount }}/{{
                results.totalResponsesCount
              }}</span
            >
          </div>
          <div
            class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
          >
            <span class="text-slate-600">{{ t("cognitiveFlexibilityTest.ruleSwitches") }}</span>
            <span class="font-semibold text-slate-800">{{
              switchTrials.length
            }}</span>
          </div>
          <div
            class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
          >
            <span class="text-slate-600">{{ t("cognitiveFlexibilityTest.switchAccuracy") }}</span>
            <span class="font-semibold text-slate-800"
              >{{ results.switchAccuracy }}%</span
            >
          </div>
          <div
            class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
          >
            <span class="text-slate-600">{{ t("cognitiveFlexibilityTest.switchCost") }}</span>
            <span class="font-semibold text-slate-800"
              >{{ results.averageSwitchCost }}ms</span
            >
          </div>
          <div
            class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
          >
            <span class="text-slate-600">{{ t("cognitiveFlexibilityTest.maxStreak") }}</span>
            <span class="font-semibold text-slate-800">{{ maxStreak }}</span>
          </div>
        </div>

        <div
          class="bg-gradient-to-r from-blue-50 to-purple-50 rounded-xl p-4 border border-blue-100"
        >
          <h3 class="font-semibold text-blue-900 mb-3 flex items-center gap-2">
            <Brain class="w-5 h-5" />
            {{ t("cognitiveFlexibilityTest.performanceAnalysis") }}
          </h3>
          <div class="space-y-2 text-sm">
            <div class="flex justify-between">
              <span class="text-slate-600">{{ t("cognitiveFlexibilityTest.baseAccuracyScore") }}</span>
              <span class="text-blue-600"
                >+{{ Math.round(results.accuracy * 0.4) }}分</span
              >
            </div>
            <div class="flex justify-between">
              <span class="text-slate-600">{{ t("cognitiveFlexibilityTest.switchAdaptability") }}</span>
              <span class="text-green-600"
                >+{{
                  Math.round(Math.max(0, results.switchAccuracy - 20) * 0.3)
                }}分</span
              >
            </div>
            <div class="flex justify-between">
              <span class="text-slate-600">{{ t("cognitiveFlexibilityTest.reactionSpeedBonus") }}</span>
              <span class="text-blue-600"
                >+{{
                  Math.round(
                    Math.max(
                      0,
                      Math.min(100, (3000 - results.averageRT) / 20)
                    ) * 0.15
                  )
                }}分</span
              >
            </div>
            <div class="flex justify-between">
              <span class="text-slate-600">{{ t("cognitiveFlexibilityTest.consistencyScore") }}</span>
              <span class="text-green-600"
                >+{{
                  Math.round(
                    (reactionTimes.length > 1
                      ? Math.max(
                          0,
                          100 -
                            Math.sqrt(
                              reactionTimes.reduce(
                                (sum, rt) => sum + Math.pow(rt - averageRT, 2),
                                0
                              ) / reactionTimes.length
                            ) /
                              20
                        )
                      : 0) * 0.1
                  )
                }}分</span
              >
            </div>
          </div>
        </div>

        <button
          class="w-full bg-gradient-to-r from-teal-600 to-cyan-500 hover:from-teal-700 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
          size="lg"
          @click="handleComplete"
        >
          {{ t("cognitiveFlexibilityTest.viewDetailedResults") }}
        </button>
      </div>
    </div>
  </div>

  <div v-else class="max-w-2xl mx-auto text-center p-8">
    <p class="text-slate-600">{{ t("cognitiveFlexibilityTest.loading") }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from "vue";
import { useI18n } from "vue-i18n";
// 假设 lucide-vue-next 已经安装并可用
import {
  Shuffle,
  Clock,
  Trophy,
  Star,
  CheckCircle,
  XCircle,
  Zap,
  Brain,
  Target,
  AlertCircle,
} from "lucide-vue-next";

const { t } = useI18n();

const emit = defineEmits(["complete"]);

const stage = ref("instructions"); // 'instructions', 'test', 'results'
const currentTrial = ref(0);
const currentRule = ref("shape");
const trials = ref([]);
const responses = ref([]);
const reactionTimes = ref([]);
const timeLeft = ref(420); // 7分钟
const startTime = ref(0);
const trialStartTime = ref(0);
const score = ref(0);
const switchTrials = ref([]);
const feedback = ref({ show: false, correct: false, reactionTime: 0 });
const streakCount = ref(0);
const maxStreak = ref(0);
const switchPerformance = ref({ correct: 0, total: 0 });
const awaitingResponse = ref(true);

const MAX_TRIALS = 80;
let feedbackTimeout = null;
let timerInterval = null;

const ruleDefinitions = computed(() => ({
  shape: {
    description: t("cognitiveFlexibilityTest.ruleDefs.shape.description"),
    criteria: t("cognitiveFlexibilityTest.ruleDefs.shape.criteria"),
    correct: ["circle", "triangle", "hexagon"],
    color: "blue",
  },
  color: {
    description: t("cognitiveFlexibilityTest.ruleDefs.color.description"),
    criteria: t("cognitiveFlexibilityTest.ruleDefs.color.criteria"),
    correct: ["red", "blue", "purple"],
    color: "purple",
  },
  size: {
    description: t("cognitiveFlexibilityTest.ruleDefs.size.description"),
    criteria: t("cognitiveFlexibilityTest.ruleDefs.size.criteria"),
    correct: ["medium", "large"],
    color: "green",
  },
  mixed: {
    description: t("cognitiveFlexibilityTest.ruleDefs.mixed.description"),
    criteria: t("cognitiveFlexibilityTest.ruleDefs.mixed.criteria"),
    correct: [], // 特殊处理
    color: "orange",
  },
}));

const generateTrials = () => {
  const shapes = ["circle", "square", "triangle", "diamond", "hexagon"];
  const colors = ["red", "blue", "green", "yellow", "purple", "orange"];
  const sizes = ["small", "medium", "large"];
  const rules = ["shape", "color", "size", "mixed"];

  const newTrials = [];
  const switchPositions = [];
  let rule = "shape";

  let nextSwitch = 12;
  while (nextSwitch < MAX_TRIALS) {
    switchPositions.push(nextSwitch);
    nextSwitch += Math.floor(Math.random() * 8) + 8;
  }

  switchTrials.value = switchPositions;

  for (let i = 0; i < MAX_TRIALS; i++) {
    if (switchPositions.includes(i)) {
      const availableRules = rules.filter((r) => r !== rule);
      rule = availableRules[Math.floor(Math.random() * availableRules.length)];
    }

    const shape = shapes[Math.floor(Math.random() * shapes.length)];
    const color = colors[Math.floor(Math.random() * colors.length)];
    const size = sizes[Math.floor(Math.random() * sizes.length)];

    let correct;
    let ruleSpecific = "";

    const currentRuleDefs = ruleDefinitions.value[rule];

    switch (rule) {
      case "shape":
        correct = currentRuleDefs.correct.includes(shape);
        ruleSpecific = `${currentRuleDefs.description}：${currentRuleDefs.criteria}`;
        break;
      case "color":
        correct = currentRuleDefs.correct.includes(color);
        ruleSpecific = `${currentRuleDefs.description}：${currentRuleDefs.criteria}`;
        break;
      case "size":
        correct = currentRuleDefs.correct.includes(size);
        ruleSpecific = `${currentRuleDefs.description}：${currentRuleDefs.criteria}`;
        break;
      case "mixed":
        correct =
          (size === "large" && color === "red") ||
          (size === "small" && color === "blue");
        ruleSpecific = `${currentRuleDefs.description}：${currentRuleDefs.criteria}`;
        break;
      default:
        correct = false;
    }

    newTrials.push({
      id: i + 1,
      shape,
      color,
      size,
      rule,
      correct,
      ruleSpecific,
    });
  }

  return newTrials;
};

const startTimer = () => {
  timerInterval = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--;
    } else {
      stage.value = "results";
      clearInterval(timerInterval);
    }
  }, 1000);
};

const handleStartTest = () => {
  stage.value = "test";
  startTime.value = Date.now();
  const newTrials = generateTrials();
  trials.value = newTrials;
  currentRule.value = newTrials[0].rule;
  trialStartTime.value = Date.now();
  startTimer();
};

const handleResponse = (userResponse) => {
  if (!awaitingResponse.value) return;

  const rt = Date.now() - trialStartTime.value;
  const trial = trials.value[currentTrial.value];
  const isCorrect = userResponse === trial.correct;
  const isSwitchTrial = switchTrials.value.includes(currentTrial.value);

  awaitingResponse.value = false;
  responses.value.push(userResponse);
  reactionTimes.value.push(rt);

  feedback.value = { show: true, correct: isCorrect, reactionTime: rt };

  if (isCorrect) {
    score.value++;
    streakCount.value++;
    maxStreak.value = Math.max(maxStreak.value, streakCount.value);
  } else {
    streakCount.value = 0;
  }

  if (isSwitchTrial) {
    switchPerformance.value.total++;
    if (isCorrect) {
      switchPerformance.value.correct++;
    }
  }

  feedbackTimeout = setTimeout(() => {
    feedback.value = { show: false, correct: false, reactionTime: 0 };
    awaitingResponse.value = true;

    if (currentTrial.value < trials.value.length - 1) {
      currentTrial.value++;
      currentRule.value = trials.value[currentTrial.value].rule;
      trialStartTime.value = Date.now();
    } else {
      stage.value = "results";
    }
  }, 1000);
};

const results = computed(() => {
  if (stage.value !== "results") {
    return {
      finalScore: 0,
      accuracy: 0,
      averageRT: 0,
      correctResponsesCount: 0,
      totalResponsesCount: 0,
      switchAccuracy: 0,
      averageSwitchCost: 0,
    };
  }

  if (
    !trials.value.length ||
    !responses.value.length ||
    !reactionTimes.value.length
  ) {
    return {
      finalScore: 0,
      accuracy: 0,
      averageRT: 0,
      correctResponsesCount: 0,
      totalResponsesCount: 0,
      switchAccuracy: 0,
      averageSwitchCost: 0,
    };
  }

  const minLength = Math.min(
    responses.value.length,
    trials.value.length,
    reactionTimes.value.length
  );
  const validResponses = responses.value.slice(0, minLength);
  const validTrials = trials.value.slice(0, minLength);
  const validReactionTimes = reactionTimes.value.slice(0, minLength);

  const correctResponses = validResponses
    .map((response, index) => response === validTrials[index]?.correct)
    .filter((result) => result !== undefined);

  const accuracy =
    correctResponses.length > 0
      ? Math.round(
          (correctResponses.filter(Boolean).length / correctResponses.length) *
            100
        )
      : 0;
  const averageRT =
    validReactionTimes.length > 0
      ? Math.round(
          validReactionTimes.reduce((sum, rt) => sum + rt, 0) /
            validReactionTimes.length
        )
      : 0;

  const switchAcc =
    switchPerformance.value.total > 0
      ? Math.round(
          (switchPerformance.value.correct / switchPerformance.value.total) *
            100
        )
      : 0;

  const switchCosts = [];
  validReactionTimes.forEach((rt, index) => {
    if (
      switchTrials.value.includes(index) &&
      index > 0 &&
      !isNaN(rt) &&
      !isNaN(validReactionTimes[index - 1])
    ) {
      switchCosts.push(rt - validReactionTimes[index - 1]);
    }
  });

  const avgSwitchCost =
    switchCosts.length > 0
      ? Math.round(
          switchCosts.reduce((sum, cost) => sum + cost, 0) / switchCosts.length
        )
      : 0;

  let finalScoreValue = 0;
  finalScoreValue += accuracy * 0.4;
  finalScoreValue += Math.max(0, switchAcc - 20) * 0.3;
  finalScoreValue += Math.max(0, Math.min(100, (3000 - averageRT) / 20)) * 0.15;

  const rtVariance =
    validReactionTimes.length > 1
      ? validReactionTimes.reduce(
          (sum, rt) => sum + Math.pow(rt - averageRT, 2),
          0
        ) / validReactionTimes.length
      : 0;
  const consistencyScore = Math.max(0, 100 - Math.sqrt(rtVariance) / 20);
  finalScoreValue += consistencyScore * 0.1;
  finalScoreValue -= Math.min(20, Math.abs(avgSwitchCost) / 50) * 0.05;

  finalScoreValue = Math.round(Math.max(0, Math.min(100, finalScoreValue)));

  return {
    finalScore: finalScoreValue,
    accuracy,
    averageRT: averageRT,
    correctResponsesCount: correctResponses.filter(Boolean).length,
    totalResponsesCount: correctResponses.length,
    switchAccuracy: switchAcc,
    averageSwitchCost: avgSwitchCost,
  };
});

const handleComplete = () => {
  const resultData = results.value;
  const timeUsed = Math.round((Date.now() - startTime.value) / 1000);

  const resultPayload = {
    id: Date.now().toString(),
    testType: "cognitive-flexibility",
    score: resultData.finalScore,
    completedAt: new Date(),
    duration: timeUsed,
    details: {
      totalTrials: resultData.totalResponsesCount,
      correctResponses: resultData.correctResponsesCount,
      accuracy: resultData.accuracy,
      averageReactionTime: resultData.averageRT,
      switchTrials: switchTrials.value.length,
      switchAccuracy: resultData.switchAccuracy,
      averageSwitchCost: resultData.averageSwitchCost,
      maxStreak: maxStreak.value,
      // ... add other detailed stats if needed
    },
  };

  emit("complete", resultPayload);
};

const progress = computed(() =>
  trials.value.length > 0
    ? ((currentTrial.value + 1) / trials.value.length) * 100
    : 0
);
const isSwitch = computed(() =>
  switchTrials.value.includes(currentTrial.value)
);

const ruleBadgeClass = computed(() => {
  switch (currentRule.value) {
    case "shape":
      return "bg-blue-100 text-blue-700 border-blue-300";
    case "color":
      return "bg-purple-100 text-purple-700 border-purple-300";
    case "size":
      return "bg-green-100 text-green-700 border-green-300";
    default:
      return "bg-orange-100 text-orange-700 border-orange-300";
  }
});

const ruleCardClass = computed(() => {
  switch (currentRule.value) {
    case "shape":
      return "from-blue-50 to-blue-100 border-blue-200";
    case "color":
      return "from-purple-50 to-purple-100 border-purple-200";
    case "size":
      return "from-green-50 to-green-100 border-green-200";
    default:
      return "from-orange-50 to-orange-100 border-orange-200";
  }
});

const ruleTextClass = computed(() => {
  switch (currentRule.value) {
    case "shape":
      return "text-blue-800";
    case "color":
      return "text-purple-800";
    case "size":
      return "text-green-800";
    default:
      return "text-orange-800";
  }
});

const currentTrialData = computed(() => trials.value[currentTrial.value] || {});

const shapeSizeClass = computed(() => {
  const sizeClasses = {
    small: "w-16 h-16",
    medium: "w-24 h-24",
    large: "w-32 h-32",
  };
  return sizeClasses[currentTrialData.value.size] || "";
});

const shapeColorClass = computed(() => {
  const colorClasses = {
    red: "bg-red-500",
    blue: "bg-blue-500",
    green: "bg-green-500",
    yellow: "bg-yellow-500",
    purple: "bg-purple-500",
    orange: "bg-orange-500",
  };
  return colorClasses[currentTrialData.value.color] || "";
});

// For Circle and Square
const simpleShapeClasses = computed(() => {
  const base = "mx-auto shadow-lg transition-all duration-300";
  const shape =
    currentTrialData.value.shape === "circle" ? "rounded-full" : "rounded-lg";
  return [base, shapeSizeClass.value, shapeColorClass.value, shape];
});

// For Triangle, Diamond, Hexagon
const complexShapeContainerClasses = computed(() => {
  return ["relative", "mx-auto", shapeSizeClass.value];
});

onMounted(() => {
  // Cleanup on unmount
  onUnmounted(() => {
    if (feedbackTimeout) clearTimeout(feedbackTimeout);
    if (timerInterval) clearInterval(timerInterval);
  });
});

watch(stage, (newStage) => {
  if (newStage === "results") {
    if (timerInterval) clearInterval(timerInterval);
  }
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.pop-enter-active,
.pop-leave-active {
  transition: transform 0.3s, opacity 0.3s;
}

.pop-enter-from,
.pop-leave-to {
  transform: scale(0);
  opacity: 0;
}

.slide-up-enter-active,
.slide-up-leave-active {
  transition: transform 0.3s, opacity 0.3s;
}

.slide-up-enter-from,
.slide-up-leave-to {
  transform: translateY(20px);
  opacity: 0;
}

.shape-rotate-enter-active {
  transition: transform 0.4s, opacity 0.4s;
  transform-style: preserve-3d;
}

.shape-rotate-leave-active {
  transition: none;
}

.shape-rotate-enter-from {
  transform: rotateY(90deg);
  opacity: 0;
}

.shape-rotate-leave-to {
  opacity: 0;
}
</style>